import json
import random
import time
import os
import pandas as pd


def random_wait():
    # 生成一个介于1到5秒之间的随机浮点数
    wait_time = random.uniform(1, 2)
    print(f"Waited for {wait_time:.2f} seconds")
    # 等待指定的秒数
    time.sleep(wait_time)


def download_image(url: str,
                   file_name: str = '',
                   file_path: str = './') -> None:
    '''
    图片下载器

    Args:
        url (str): 图片链接
        file_name (str): 文件名(需后缀)
        file_path (str): 保存目录
    '''
    if file_name == '':
        file_name = url.split('/')[-1]
    try:
        response = session.get(url)
        response.raise_for_status()
        with open(file_path + file_name, 'wb') as f:
            f.write(response.content)
        print(f'[Download Success] {file_name} ')
    except Exception as e:
        print(e)
    finally:
        random_wait()


def load_json_to_dict(file_path: str) -> dict:
    '''
    读取`json`并转化为`dict`
    :param {str} file_path
    :return {*}
    '''
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)


def save_dict_to_json(data: dict, file_path: str) -> None:
    '''
    将`dict`转化为`json`并保存

    Args:
        data (dict): dict数据
        file_path (str): 保存目录
    '''

    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False)
        print(f'Save {file_path} Success')


def process_excel(file_path, output_json_path):
    """
    获取rj exlce中的货号保存为`json`

    Args:
        file_path (_type_): excle文件路径
        output_json_path (_type_): json文件输出路径
    """
    # 读取 Excel 文件, 忽略前两行
    df = pd.read_excel(file_path, engine='openpyxl', skiprows=2)

    # 检查数据框是否为空
    if df.empty:
        print("数据框为空, 无法处理.")
        return

    # 获取第一列数据并转换为列表
    first_column_data = df.iloc[:, 0].tolist()

    # 将列表导出为 JSON 格式
    with open(output_json_path, 'w', encoding='utf-8') as json_file:
        json.dump(first_column_data, json_file, ensure_ascii=False, indent=4)

    print(f"第一列数据已成功导出到 {output_json_path}")


def load_xlxs_to_list(file_path: str,
                      columns_to_load: list,
                      sheet_name: str = 'Sheet1') -> list:
    '''
    读取`xlsx`并转化为`list`
    
    Args:
    file_path (str): excle文件路径
    columns_to_load (list): 需要加载的列
    sheet_name (str): 加载的表名
    
    '''
    # 加载指定列
    data = pd.read_excel(file_path,
                         sheet_name=sheet_name,
                         usecols=columns_to_load)
    values_list = data[columns_to_load].values.flatten().tolist()
    return values_list


def load_xlxs_to_dict(file_path: str, sheet_name: str = 'Sheet1') -> dict:
    '''
    读取`xlsx`并转化为`dict`

    Args:
    file_path (str): excle文件路径
    sheet_name (str): 加载的表名

    '''
    # 加载指定列
    data = pd.read_excel(file_path, sheet_name=sheet_name)
    values_dict = data.to_dict(orient='records')
    return values_dict


def process_string(input_string):
    """删除规格

    Args:
        input_string (_type_): _description_

    Returns:
        _type_: 返回货号
    """
    # 分割字符串
    parts = input_string.split('-')

    # 判断 '-' 的数量
    if len(parts) >= 3:
        # 如果有两个或更多 '-', 去掉最后一部分
        return '-'.join(parts[:-1])
    else:
        # 否则，返回原字符串
        return input_string


def split_list(original_list, chunk_size=50):
    """将列表拆分为多个子列表，每个子列表最多包含 chunk_size 个元素。"""
    return [
        original_list[i:i + chunk_size]
        for i in range(0, len(original_list), chunk_size)
    ]


# if __name__ == '__main__':
#     download_image('https://img.macklin.cn/img/item/000/81/26541800.gif')


def merge_json_files(directory):
    """_summary_

    Args:
        directory (_type_):json文件夹路径
    """
    result = []

    # 遍历指定目录
    for filename in os.listdir(directory):
        if filename.endswith('.json'):  # 确认文件是JSON格式
            filepath = os.path.join(directory, filename)
            with open(filepath, 'r', encoding='utf-8') as file:
                data = json.load(file)
                result = result + data

    # 将合并后的数据保存到新的JSON文件中
    with open('merged_file.json', 'w', encoding='utf-8') as output_file:
        json.dump(result, output_file, ensure_ascii=False, indent=4)
